package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.adapter.MyOnScroll;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.bean.WDGLBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/11/22.
 */

public class MyHDActivity extends BaseActivity {

    @Bind(R.id.my_answer_bsfh)
    ImageView myAnswerBsfh;
    @Bind(R.id.my_answer_bj)
    TextView myAnswerBj;
    @Bind(R.id.my_answer_recyclerview)
    RecyclerView myAnswerRecyclerview;
    @Bind(R.id.my_answer_qx)
    TextView myAnswerQx;
    @Bind(R.id.my_answer_sc)
    TextView myAnswerSc;
    @Bind(R.id.my_answer_ll)
    LinearLayout myAnswerLl;

    private int current_page = 1;
    private int per_page = 10;
    View error_head;
    WDGLBean mYcollectionbean;
    ArrayList<WDGLBean.DataBean.PutForwardBean> mdata = new ArrayList<>();
    BaseAdapter<WDGLBean.DataBean.PutForwardBean> adapter;
    ArrayList<String> refer_id = new ArrayList<String>(){
        @Override
        public String toString() {
            String s= "";
            for (String info: refer_id) {
                s = s+ info+",";
            }
            return s;
        }
    };
    private boolean isDataChange = false;
    private View footerview;//加载更多

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_answer_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        footerview = LayoutInflater.from(this).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        requsetHD();
    }


    /**
     * 我的问题请求
     */
    private void requsetHD() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("genre",3+"");//01我提出的问题2我收到的问题3我回答的问题
        map.put("current_page",current_page+"");
        map.put("per_page",per_page+"");

        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_WDGL_New;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, WDGLBean.class, URLAddress.URLBASE + URLAddress.URL_WDGL_New, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                mYcollectionbean = (WDGLBean) response;
                if (mYcollectionbean.getData()==null){
                    //mYcollectionbean.setData(new ArrayList<>());
                }
                if (mYcollectionbean.getResult() == 1 && current_page == 1){
                    List l = mYcollectionbean.getData().getPutForward();
                    if (l==null){
                        l = new ArrayList();
                    }
                    mdata.addAll(l);
                    current_page = current_page + 1;
                    initView();
                    footerview.setVisibility(View.INVISIBLE);
                }else if(mYcollectionbean.getResult() == 1){
                    current_page = current_page + 1;
                    List l = mYcollectionbean.getData().getPutForward();
                    if (l==null){
                        l = new ArrayList();
                    }
                    mdata.addAll(l);
                    adapter.notifyDataSetChanged();
                    footerview.setVisibility(View.INVISIBLE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                footerview.setVisibility(View.INVISIBLE);
                // Toasts.show(MyAnswerActivity.this, "没有数据了", Toast.LENGTH_SHORT);
            }
        });
    }

    private void initView() {
        adapter = new BaseAdapter<WDGLBean.DataBean.PutForwardBean>(this,mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, WDGLBean.DataBean.PutForwardBean referBean) {
                initItem(holder,referBean);
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_my_collection_item;
            }
        };




        /**
         * 添砖到问题详情，回答问题
         */
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(MyHDActivity.this, WTContentActivity.class);
                //SampleApplicationLike.getQueueInstance().cancelAll("tag");
                intent.putExtra("refer_id",mdata.get(position).getId());
                startActivity(intent);
            }
        });
        adapter.addFootView(footerview);
        myAnswerRecyclerview.setLayoutManager(new LinearLayoutManager(MyHDActivity.this));
        if (mdata.size() == 0 ){
            error_head = LayoutInflater.from(MyHDActivity.this).inflate(R.layout.view_item_error,myAnswerRecyclerview,false);
            ((TextView)error_head.findViewById(R.id.text_view_error)).setText("您尚未回答任何问题");
            adapter.addHeaderView(error_head);
        }

        myAnswerRecyclerview.setAdapter(adapter);
        loadMore();
    }

    /**
     * 开启加载更多
     */
    private void loadMore() {

        myAnswerRecyclerview.addOnScrollListener(new MyOnScroll(){
            @Override
            public void scrollBottom() {

                super.scrollBottom();
                footerview.setVisibility(View.VISIBLE);
                requsetHD();


            }
        });
    }



    private void initItem(final BaseAdapter<WDGLBean.DataBean.PutForwardBean>.BaseViewHolder holder, final WDGLBean.DataBean.PutForwardBean referBean) {
        ((CheckBox)holder.getView(R.id.checkBox3)).setChecked(referBean.isChoose());
        if (referBean.getIsShowCheckBod() == View.VISIBLE){
            ((CheckBox)holder.getView(R.id.checkBox3)).setVisibility(View.VISIBLE);
        }else{
            ((CheckBox)holder.getView(R.id.checkBox3)).setVisibility(View.GONE);
        }

        ((CheckBox)holder.getView(R.id.checkBox3)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    refer_id.add(referBean.getId()+"");
                }else{
                    refer_id.remove(referBean.getId()+"");
                }
            }
        });

        /**
         * todo 填充数据
         */
        ((TextView)holder.getView(R.id.textView63)).setText(referBean.getTitle());
        ((TextView)holder.getView(R.id.textView64)).setText(referBean.getCollect_count()+"收藏");
        ((TextView)holder.getView(R.id.textView65)).setText(referBean.getAnswer_count()+"回答");
        ((TextView)holder.getView(R.id.textView66)).setText(referBean.getCreate_time());
    }


    @OnClick({R.id.my_answer_bsfh, R.id.my_answer_bj, R.id.my_answer_qx, R.id.my_answer_sc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.my_answer_bsfh:
                finish();
                break;
            case R.id.my_answer_bj:
                if (mdata.size()>0){
                    try {
                        if (((TextView)view).getText().toString().equals("编辑")) {
                            ((TextView)view).setText("取消");
                            myAnswerLl.setVisibility(View.VISIBLE);
                            adapter.isClickable(new BaseAdapter.IsClickable() {
                                @Override
                                public boolean isClickable() {
                                    return false;
                                }
                            });
                            for (int i = 0; i < mdata.size(); i++) {
                                mdata.get(i).setIsShowCheckBod(View.VISIBLE);
                            }
                        }else{
                            myAnswerRecyclerview.setClickable(true);
                            adapter.isClickable(new BaseAdapter.IsClickable() {
                                @Override
                                public boolean isClickable() {
                                    return true;
                                }
                            });
                            ((TextView)view).setText("编辑");
                            myAnswerLl.setVisibility(View.GONE);
                            for (int i = 0; i < mdata.size(); i++) {
                                mdata.get(i).setIsShowCheckBod(View.GONE);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }catch (Exception e){
                        Toasts.show(this, "没有数据呀", Toast.LENGTH_SHORT);
                    }
                }else{
                    Toasts.show(this, "没有数据呀", Toast.LENGTH_SHORT);
                }
                break;
            case R.id.my_answer_qx:
                if (((TextView)view).getText().toString().equals("全选")) {
                    ((TextView)view).setText("全不选");
                    for (int i = 0; i < mdata.size(); i++) {
                        mdata.get(i).setChoose(true);
                    }
                }else{
                    ((TextView)view).setText("全选");
                    for (int i = 0; i < mdata.size(); i++) {
                        mdata.get(i).setChoose(false);
                    }
                }



                adapter.notifyDataSetChanged();
                break;
            case R.id.my_answer_sc:
                requestDelWD();//执行取消收藏操作
                break;
        }
    }
    /**
     * 取消收藏
     */
    private void requestDelWD() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("refer_id",refer_id.toString());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_DEL_HD, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                RzBean rZBean = (RzBean) response;
                if (rZBean.getResult() == 1){
                    isDataChange = true;
                    startActivity(new Intent(MyHDActivity.this,MyHDActivity.class));
                    finish();
//                    requsetHD();
//                    com.example.administrator.szb.adapter.notifyDataSetChanged();
                }else {
                    Toasts.show(MyHDActivity.this, ""+rZBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toasts.show(MyHDActivity.this, "请选中要删除的数据哟", Toast.LENGTH_SHORT);
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isDataChange) {
          //  HomeActivity.isLogin_or_register = true;
        }
        finish();
    }
}
